import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { SensitiveWord } from '../../entities/sensitive-word.entity';

@Injectable()
export class SensitiveWordService {
  constructor(
    @InjectRepository(SensitiveWord)
    private sensitiveWordRepository: Repository<SensitiveWord>,
  ) {}

  /**
   * 获取所有敏感词
   */
  async findAll() {
    return this.sensitiveWordRepository.find({
      where: { isActive: 1 },
      order: { usageCount: 'DESC' },
    });
  }

  /**
   * 获取所有敏感词（包括禁用的）
   */
  async findAllAdmin() {
    return this.sensitiveWordRepository.find({
      order: { usageCount: 'DESC' },
    });
  }

  /**
   * 根据ID获取敏感词
   */
  async findOne(id: number) {
    return this.sensitiveWordRepository.findOne({ where: { id } });
  }

  /**
   * 创建敏感词
   */
  async create(word: string) {
    // 检查是否已存在
    const existing = await this.sensitiveWordRepository.findOne({
      where: { word },
    });

    if (existing) {
      throw new HttpException('该敏感词已存在', HttpStatus.BAD_REQUEST);
    }

    const sensitiveWord = this.sensitiveWordRepository.create({
      word,
      isActive: 1,
    });

    return this.sensitiveWordRepository.save(sensitiveWord);
  }

  /**
   * 批量创建敏感词
   */
  async createBatch(words: string[]) {
    const result = {
      success: 0,
      failed: 0,
      details: [] as string[],
    };

    for (const word of words) {
      try {
        await this.create(word);
        result.success++;
      } catch (error) {
        result.failed++;
        result.details.push(`${word}: ${error.message}`);
      }
    }

    return result;
  }

  /**
   * 更新敏感词
   */
  async update(id: number, word: string) {
    const sensitiveWord = await this.findOne(id);
    if (!sensitiveWord) {
      throw new HttpException('敏感词不存在', HttpStatus.NOT_FOUND);
    }

    await this.sensitiveWordRepository.update(id, { word });
    return this.findOne(id);
  }

  /**
   * 删除敏感词
   */
  async remove(id: number) {
    const sensitiveWord = await this.findOne(id);
    if (!sensitiveWord) {
      throw new HttpException('敏感词不存在', HttpStatus.NOT_FOUND);
    }

    await this.sensitiveWordRepository.delete(id);
    return { success: true, message: '删除成功' };
  }

  /**
   * 批量删除敏感词
   */
  async removeBatch(ids: number[]) {
    await this.sensitiveWordRepository.delete(ids);
    return { success: true, message: '批量删除成功' };
  }

  /**
   * 更新敏感词状态
   */
  async updateStatus(id: number, isActive: number) {
    const sensitiveWord = await this.findOne(id);
    if (!sensitiveWord) {
      throw new HttpException('敏感词不存在', HttpStatus.NOT_FOUND);
    }

    await this.sensitiveWordRepository.update(id, { isActive });
    return this.findOne(id);
  }

  /**
   * 增加敏感词使用次数
   */
  async incrementUsageCount(word: string) {
    const sensitiveWord = await this.sensitiveWordRepository.findOne({
      where: { word },
    });

    if (sensitiveWord) {
      sensitiveWord.usageCount += 1;
      await this.sensitiveWordRepository.save(sensitiveWord);
    }
  }

  /**
   * 过滤文本中的敏感词，替换为 *
   */
  async filterSensitiveWords(text: string): Promise<{ 
    filteredText: string; 
    hasSensitive: boolean;
    matchedWords: string[];
  }> {
    const sensitiveWords = await this.findAll();
    let filteredText = text;
    const matchedWords: string[] = [];

    for (const item of sensitiveWords) {
      const regex = new RegExp(item.word, 'gi');
      if (regex.test(filteredText)) {
        matchedWords.push(item.word);
        // 增加使用次数
        await this.incrementUsageCount(item.word);
        // 替换为 *
        filteredText = filteredText.replace(regex, '*'.repeat(item.word.length));
      }
    }

    return {
      filteredText,
      hasSensitive: matchedWords.length > 0,
      matchedWords,
    };
  }
}
